package com.rpcfx.transports;

import com.rpcfx.api.RpcfxException;
import com.rpcfx.api.Serialization;
import com.rpcfx.api.spi.ProtobufSerialization;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.concurrent.DefaultThreadFactory;

import java.net.URI;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class NettyHttpClient {

    private Bootstrap bootstrap;

    private NioEventLoopGroup executors;


    public NettyHttpClient() {
        executors = new NioEventLoopGroup(5, new DefaultThreadFactory("request-io¬"));
        bootstrap = new Bootstrap();
        bootstrap.group(executors)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, false)
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_RCVBUF, 1024 * 1024 * 3)
                .option(ChannelOption.SO_SNDBUF, 1024 * 1024 * 3)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();

                        //     pipeline.addLast(new HttpResponseDecoder());
                        //   pipeline.addLast(new HttpRequestEncoder());
                        pipeline.addLast(new HttpClientCodec());
                        pipeline.addLast(new HttpObjectAggregator(1024 * 10 * 1024));

                        pipeline.addLast("nettyHttpClientHandler", new NettyHttpClientHandler());

                    }
                });
    }


    public Object post(String url, String methodName, Object[] args, boolean oneWay) {
        try {

            String host = url.substring(0, url.indexOf("/"));
            String[] strings = host.split(":");
            String hostIp = strings[0];
            String port = "80";
            if (strings.length == 2) {
                port = strings[1];
            }

            ChannelFuture connect = bootstrap.connect(hostIp, Integer.parseInt(port)).sync();

            Channel channel = connect.channel();
            URI uri = URI.create(url.substring(url.indexOf("/")));


            Serialization serialization = new ProtobufSerialization();
            ByteBuf content = Unpooled.buffer();
            TransportParam transportParam = new TransportParam();
            transportParam.setMethodName(methodName);
            transportParam.setArgs(args);
            transportParam.setOneWay(oneWay);
            byte[] param = serialization.serialize(transportParam);
            content.writeBytes(param);
            FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString(), content);
            ResponseFuture responseFuture = new ResponseFuture();
            channel.pipeline().get(NettyHttpClientHandler.class).setResponseFuture(responseFuture);
            request.headers()
                    .set(HttpHeaderNames.CONTENT_TYPE, "application/octet-stream")
                    //开启长连接
                    //   .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE)
                    //设置传递请求内容的长度
                    .set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes())
                    .set(HttpHeaderNames.HOST, NetUtils.getLocalInetAddress().getHostName());
            channel.writeAndFlush(request).sync();
            byte[] bytes = null;
            if (oneWay) {
                channel.close();
            } else {
                bytes = responseFuture.get(2000, TimeUnit.MILLISECONDS);
                channel.close();
            }
            return bytes;
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            throw new RpcfxException(-1, e.getMessage());
        } finally {
            executors.shutdownGracefully();
        }
    }
}
